/*
 * Created using SharpDevelop.
 * User: Steve
 * Date: 4/11/2006
 * Time: 11:29 AM
 * 
 */

using System;
using System.Xml;

using Mokey.Common;
using Mokey.ThunderCards.XmlElementNames;
using System.IO;
using Mokey.Common.Forms;

namespace Mokey.ThunderCards.Settings
{
	/// <summary>
	/// Description of SettingsFile.
	/// </summary>
	public class SettingsFile
	{
		public SettingsFile(string filePath)
		{
			_filePath = filePath;
			XmlDocument settingsXmlFile = new XmlDocument();
            try
            {
                if (File.Exists(filePath))
                {
                    settingsXmlFile.Load(filePath);
                    LoadSettingsFromXML(settingsXmlFile);
                }
                else
                {
                    UIHelper.DisplayInfoMessage(string.Format("Settings could not be loaded. Could not find file: {0}", filePath));
                }
            }
            catch (Exception e)
            {
                UIHelper.DisplayErrorMessage(string.Format("Settings could not be loaded.\nError occurred: {0}", e.Message));
            }
		}
		
		#region Constants
		
		private const int DEFAULT_POP_UP_FREQUENCY = 300;
		private const int DEFAULT_POP_UP_DISPLAY_TIME = 10;
		private const SoundStatusEnum DEFAULT_SOUND_STATUS = SoundStatusEnum.AutoPlay;
		private const bool DEFAULT_AUTO_SHOW_QUESTIONS = true;
		private const bool DEFAULT_AUTO_SHOW_ANSWERS = true;
		private const int DEFAULT_POP_UP_WIDTH = 300;
		private const int DEFAULT_POP_UP_HEIGHT = 300;
		
		#endregion
		
		#region Private Fields
		
		private string _filePath;
		private int _popUpFrequency;
		private int _popUpDisplayTime;
		private SoundStatusEnum _soundStatus;
		private bool _autoShowQuestions;
		private bool _autoShowAnswers;
		private int _popUpWidth;
		private int _popUpHeight;
		
		#endregion
		
		#region Private Methods
		
		private void SaveSettingsToXML(XmlWriter fileToWrite)
		{
            fileToWrite.WriteStartDocument();
            fileToWrite.WriteStartElement(SettingsElements.Root_Settings);
            fileToWrite.WriteStartElement(SettingsElements.PopUpFormSettings, SettingsElements.Root_Settings);
            WritePopUpFormSetting(fileToWrite, SettingsElements.PopUpFormSettingsElements.AutoShowAnswers, AutoShowAnswers);
            WritePopUpFormSetting(fileToWrite, SettingsElements.PopUpFormSettingsElements.AutoShowQuestions, AutoShowQuestions);
            WritePopUpFormSetting(fileToWrite, SettingsElements.PopUpFormSettingsElements.PopUpDisplayTime, PopUpDisplayTime);
            WritePopUpFormSetting(fileToWrite, SettingsElements.PopUpFormSettingsElements.PopUpFrequency, PopUpFrequency);
            WritePopUpFormSetting(fileToWrite, SettingsElements.PopUpFormSettingsElements.PopUpHeight, PopUpHeight);
            WritePopUpFormSetting(fileToWrite, SettingsElements.PopUpFormSettingsElements.PopUpWidth, PopUpWidth);
            WritePopUpFormSetting(fileToWrite, SettingsElements.PopUpFormSettingsElements.SoundStatus, SoundStatus);
            WritePopUpFormSetting(fileToWrite, SettingsElements.PopUpFormSettingsElements.LastOpenedCardPack, LastOpenedCardPack);
            WritePopUpFormSetting(fileToWrite, SettingsElements.PopUpFormSettingsElements.AutoStartCardShow, AutoStartCardShow);
            
            fileToWrite.WriteEndDocument();
            fileToWrite.Flush();
		}

        private void WritePopUpFormSetting(XmlWriter fileToWrite, string tagName, object value)
        {
            fileToWrite.WriteStartElement(tagName, SettingsElements.PopUpFormSettings);
            fileToWrite.WriteValue((value ?? string.Empty).ToString());
            fileToWrite.WriteEndElement();
        }
		
		private void LoadSettingsFromXML(XmlDocument settingsXmlFile)
		{
			XmlElement popUpFormSettings = settingsXmlFile.DocumentElement[SettingsElements.PopUpFormSettings];
			if (!IntegerHelper.TryParseOrDefault(popUpFormSettings[SettingsElements.PopUpFormSettingsElements.PopUpFrequency].InnerText.Trim(), 
			                  out _popUpFrequency, DEFAULT_POP_UP_FREQUENCY))
			{
				ShowSettingLoadError("Pop Up Frequency", DEFAULT_POP_UP_FREQUENCY.ToString());
			}
			
			if (!IntegerHelper.TryParseOrDefault(popUpFormSettings[SettingsElements.PopUpFormSettingsElements.PopUpDisplayTime].InnerText.Trim(), 
			                  out _popUpDisplayTime, DEFAULT_POP_UP_DISPLAY_TIME))
			{
				ShowSettingLoadError("Pop Up Display Time", DEFAULT_POP_UP_DISPLAY_TIME.ToString());
			}
			
            try
            {
                _soundStatus = (SoundStatusEnum)Enum.Parse(typeof(SoundStatusEnum), popUpFormSettings[SettingsElements.PopUpFormSettingsElements.SoundStatus].InnerText.Trim());
            }
            catch (Exception)
            {
                _soundStatus = DEFAULT_SOUND_STATUS;
				ShowSettingLoadError("Sound", DEFAULT_SOUND_STATUS.ToString());
            }
			
			if (!BooleanHelper.TryParseOrDefault(popUpFormSettings[SettingsElements.PopUpFormSettingsElements.AutoShowQuestions].InnerText.Trim(), 
			                   out _autoShowQuestions, DEFAULT_AUTO_SHOW_QUESTIONS))
			{
				ShowSettingLoadError("Automatically Show Questions", DEFAULT_AUTO_SHOW_QUESTIONS.ToString());
			}
			
			if (!BooleanHelper.TryParseOrDefault(popUpFormSettings[SettingsElements.PopUpFormSettingsElements.AutoShowAnswers].InnerText.Trim(), 
			                   out _autoShowAnswers, DEFAULT_AUTO_SHOW_ANSWERS))
			{
				ShowSettingLoadError("Automatically Show Answers", DEFAULT_AUTO_SHOW_ANSWERS.ToString());
			}
			
			if (!IntegerHelper.TryParseOrDefault(popUpFormSettings[SettingsElements.PopUpFormSettingsElements.PopUpWidth].InnerText.Trim(), 
			                  out _popUpWidth, DEFAULT_POP_UP_WIDTH))
			{
				ShowSettingLoadError("Pop Up Width", DEFAULT_POP_UP_WIDTH.ToString());
			}
			
			if (!IntegerHelper.TryParseOrDefault(popUpFormSettings[SettingsElements.PopUpFormSettingsElements.PopUpHeight].InnerText.Trim(), 
			                  out _popUpHeight, DEFAULT_POP_UP_HEIGHT))
			{
				ShowSettingLoadError("Pop Up Height", DEFAULT_POP_UP_HEIGHT.ToString());
			}

            if (popUpFormSettings[SettingsElements.PopUpFormSettingsElements.LastOpenedCardPack] != null)
            {
                LastOpenedCardPack = popUpFormSettings[SettingsElements.PopUpFormSettingsElements.LastOpenedCardPack].InnerText.Trim();
            }

            if (popUpFormSettings[SettingsElements.PopUpFormSettingsElements.AutoStartCardShow] != null)
            {
                AutoStartCardShow = bool.Parse(popUpFormSettings[SettingsElements.PopUpFormSettingsElements.AutoStartCardShow].InnerText.Trim());
            }
		}
		
		/// <summary>
		/// Use this when something goes wrong with loading a specific setting from the xml file
		/// </summary>
		/// <param name="failedSettingName">The setting that failed to load</param>
		/// <param name="valueDefaultingTo">The value that setting has been defaulted to</param>
		private void ShowSettingLoadError(string failedSettingName, string valueDefaultingTo)
		{
			UIHelper.DisplayInfoMessage(string.Format("Error loading setting \"{0}\". Defaulting to \"{1}\".", 
			                                          failedSettingName, valueDefaultingTo));
		}
		
		#endregion
		
		#region Public Fields

        public void Save()
        {
            FileStream fs = null;
            XmlWriter xmlWriter = null;
            try
            {
                fs = File.Open(_filePath, FileMode.Create, FileAccess.Write);
                xmlWriter = XmlWriter.Create(fs);
                SaveSettingsToXML(xmlWriter);
            }
            catch (Exception e)
            {
                UIHelper.DisplayErrorMessage(string.Format("Settings could not be saved.\nError occurred: {0}", e.Message));
            }
            finally
            {
                if (xmlWriter != null)
                {
                    xmlWriter.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

		public int PopUpFrequency {
			get {
				return _popUpFrequency;
			}
			set {
				_popUpFrequency = value;
			}
		}
		
		public int PopUpDisplayTime {
			get {
				return _popUpDisplayTime;
			}
			set {
				_popUpDisplayTime = value;
			}
		}
		
		public SoundStatusEnum SoundStatus {
			get {
				return _soundStatus;
			}
			set {
				_soundStatus = value;
			}
		}
		
		public bool AutoShowQuestions {
			get {
				return _autoShowQuestions;
			}
			set {
				_autoShowQuestions = value;
			}
		}
		
		public bool AutoShowAnswers {
			get {
				return _autoShowAnswers;
			}
			set {
				_autoShowAnswers = value;
			}
		}

        public int PopUpHeight 
        {
            get
            {
                return _popUpHeight;
            }
            set
            {
                _popUpHeight = value;
            }
        }

        public int PopUpWidth
        {
            get
            {
                return _popUpWidth;
            }
            set
            {
                _popUpWidth = value;
            }
        }

        public string LastOpenedCardPack { get; set; }

        public bool AutoStartCardShow { get; set; }

		#endregion
		
	}
	
	public enum SoundStatusEnum
	{
		AutoPlay = 1,
		ManualPlay = 2,
		Disabled = 3
	}
}
